$(function () {
    var addIndex; // 弹框的ID,记录方便调用layer.close
    var treetableRender; // 树状表对象，方便刷新
    var departmentList; // 数据总记录
    var expend = true;
    layui.config({
        base: '/gzht/lib/layui/'
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['treetable'], function () {
        var treetable = layui.treetable;
        // 渲染表格
        layer.load(2);
        treetableRender = function () {
            treetable.render({
                treeColIndex: 2,
                treeSpid: "",
                treeIdName: 'departmentNo',
                treePidName: 'departmentParentNo',
                treeDefaultClose: false,
                treeLinkage: true,
                elem: '#table1',
                url: '/gzht/department/getDepTreetable',
                toolbar: '#h_tool',
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'departmentNo', title: '编号'},
                    {field: 'departmentName', title: '部门名称'},
                    {
                        field: 'departmentStatus', title: '状态', templet: function (value, item) {
                            var status = "";
                            switch (value.departmentStatus) {
                                case 0:
                                    status = "<span class=\"layui-badge layui-bg-green\">正常</span>"
                                    break;
                                case 1:
                                    status = "<span class=\"layui-badge layui-bg-gray\">禁用</span>";
                                    break;
                                default:
                                    status = "<span class=\"layui-badge\">异常</span>";
                                    break;
                            }
                            return status;
                        }
                    },
                    {field: 'departmentRemark', title: '备注信息'},
                    {fixed: 'right', title: '操作', toolbar: '#col_tool'},
                ]],
                done: function (res) {
                    departmentList = res.data || [];
                    console.log(res)
                    layer.closeAll('loading');
                }
            })
        }
        treetableRender();
    });
    layui.use(['table','treetable','form'],function () {
        var table = layui.table
            ,treetable=layui.treetable
            ,form = layui.form;
        table.on('toolbar(table1)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'h_add':
                    addIndex = layer.open({
                        type: 1,
                        content: $('#addDepFormArea'),
                        area: '600px'
                    })
                    break;
                case 'h_expend':
                    if(!expend){
                        treetable.expandAll('#table1');
                    }else {
                        treetable.foldAll('#table1');
                    }
                    expend = !expend;
                    break;
            };
        });
        table.on('tool(table1)', function(obj){
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event;
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'col_del'){ //删除
                layer.confirm('确定删除该部门及所属部门？', function(index){
                    console.log(data)
                    // obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    $.ajax({
                        url: '/gzht/department/delAllChild',
                        data: {
                            departmentNo: data.departmentNo
                        },
                        type: 'post',
                        success: function (res) {
                            if(res.code == 1001){
                                treetableRender();
                            }
                        }
                    })
                    layer.close(index);
                });
            } else if(layEvent === 'col_edit'){ //编辑
                // 查询该部门父级名称
                var parentName = "";
                if(data.departmentParentNo){
                    for(var item of departmentList){
                        if(item.departmentNo == data.departmentParentNo){
                            parentName = item.departmentName
                        }
                    }
                }
                form.val("editForm", {
                    "departmentRemark": data.departmentRemark
                    ,"departmentStatus": data.departmentStatus == 0 ? 1 : 0
                    ,"departmentName": data.departmentName
                    ,"departmentNo": data.departmentNo
                    ,"departmentParentNo": data.departmentParentNo
                    ,"departmentParentName": parentName
                })
                addIndex = layer.open({
                    type: 1,
                    content: $('#editDepFormArea'),
                    area: '600px'
                })
                //同步更新缓存对应的值
                /*obj.update({
                    username: '123'
                    ,title: 'xxx'
                });*/
            }
        });
    })
    layui.use('tree', function () {
        var tree = layui.tree;
        /*请求获取部门列表*/
        $.ajax({
            url: '/gzht/department/getAll',
            success: function (res) {
                var deps = res || [];
                var data = deps.map(function (item) {
                    return {
                        title: item.departmentName,
                        id: item.departmentNo,
                        pid: item.departmentParentNo,
                        disabled: item.departmentStatus == 1 ? true : false,
                        spread: true
                    }
                });
                var depTree = trans_tree(data);
                tree.render({
                    elem: '#part' //默认是点击节点可进行收缩
                    , data: depTree,
                    onlyIconControl: true,
                    click: function (obj) {
                        console.log(obj.elem)
                        $('.layui-tree-main').removeClass('dep_bg_red')
                        $(obj.elem).children('.layui-tree-entry').children('.layui-tree-main').addClass('dep_bg_red')
                        $.addAdminSelectDep = obj.data
                    }
                });
            },
            fail: function () {
                layer.msg("网络出错")
            }
        })

        /*监听部门选择*/
        $('#showPart,#edit_showPart').click(function () {
            var here = $(this);
            layer.open({
                type: 1,
                area: '400px',
                fixed: false, //不固定
                maxmin: true,
                content: $('#part'),
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    // 确定
                    if(here.attr('id') == 'edit_showPart'){
                        $('#edit_showPart').val($.addAdminSelectDep.title);
                        $('#edit_submitDep').val($.addAdminSelectDep.id);
                    }else if(here.attr('id') == 'showPart'){
                        $('#showPart').val($.addAdminSelectDep.title);
                        $('#submitDep').val($.addAdminSelectDep.id);
                    }
                    layer.close(index)
                },
                btn2: function (index, layero) {
                    // 取消
                }
            });
        })
    })

    layui.use('form', function () {
        var form = layui.form;
        form.render();
        /*表单验证*/
        form.verify({
            departmentName: function (value, item) {
                if(value.trim() == ''){
                    return '部门名称不得为空'
                }
                if(!/^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$/.test(value)){
                    return '部门名称不能包含特殊字符'
                }
            }
        });

        //监听新增提交
        form.on('submit(addDepSubmit)', function(data){
            var formData = new FormData($('#addDepForm')[0]);
            $.ajax({
                url: '/gzht/department/addDepartment',
                data: formData,
                type: 'post',
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (res) {
                    if(res.code == 1001){
                        layer.msg("添加成功",{
                            icon: 1,
                            time: 600
                        }, function(){
                            layer.close(addIndex);
                            treetableRender();
                        });
                    }else {
                        layer.msg('添加失败')
                    }
                },
                fail: function (err) {
                    layer.msg("网络出错")
                }
            })
            return false;
        });
        //监听编辑提交
        form.on('submit(editDepSubmit)',function (data) {
            var formData = new FormData($('#editDepForm')[0]);
            $.ajax({
                url: '/gzht/department/editDepartment',
                data: formData,
                type: 'post',
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (res) {
                    if(res.code == 1001){
                        layer.msg("编辑成功",{
                            icon: 1,
                            time: 600
                        }, function(){
                            layer.close(addIndex);
                            treetableRender();
                        });
                    }else {
                        layer.msg('编辑失败')
                    }
                },
                fail: function (err) {
                    layer.msg("网络出错")
                }
            })
            return false;
        })
    })
})
